package com.yao_shop.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.yao_shop.service.token_service;
import com.yao_shop.utils.RedisUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class token_serviceImpl implements token_service {
    @Resource
    private RedisUtil redisUtil;
//生成token 返回控制层
    @Override
    public String generateToken(String userAgentStr,String stu_phone) {
        StringBuilder token = new StringBuilder();
        //设备
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
        if (userAgent.getOperatingSystem().isMobileDevice()) {
            token.append("MOBILE-");
        } else {
            token.append("PC-");
        }
        //加密的用户名
        token.append(DigestUtils.md5Hex(stu_phone) + "-");
        //时间
        token.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "-");
        //六位随机字符串
        token.append(new Random().nextInt(999999 - 111111 + 1) + 111111 );
        System.out.println("token-->" + token.toString());
        return token.toString();

    }
//将tokne存入redis 并判断是否为pc端并插入生效时间
    @Override
    public void save(String token, Map login_info) {
        if (token.startsWith("PC")) {
            redisUtil.set(token, JSONObject.toJSONString(login_info));
            redisUtil.expire(token,60*60);
        } else {
            redisUtil.set(token, JSONObject.toJSONString(login_info));
            redisUtil.expire(token,60*60);
        }

    }
//判断token是否存在
    @Override
    public boolean panduan(String token) {
        try{
            boolean b = redisUtil.hasKey(token);
            return true;

        }catch (Exception e) {
            e.getMessage();
            return false;
        }
    }
//判断成功取出用户信息
    @Override
    public String gettoken_info(String token) {
        Object o = redisUtil.get(token);
        return o.toString();
    }
    //删除token==注销
    @Override
    public void logout(String token){
        redisUtil.del(token);
    }

}
